package com.jnevision.handclap.controller;

import java.util.StringJoiner;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crtland.landoss.LandOss;
import com.crtland.landoss.Oss;
import com.crtland.landoss.OssInfo;
import com.crtland.landoss.OssType;
import com.crtland.landoss.PathEnum;
import com.crtland.landoss.Result;
import com.jnevision.common.CommonQuery;
import com.jnevision.dept.service.DeptServiceImpl;
import com.jnevision.handclap.model.HandClap;
import com.jnevision.handclap.service.HandClapServiceImpl;
import com.jnevision.user.model.User;
import com.jnevision.user.service.UserServiceImpl;
import com.jnevision.userdept.service.UserDeptServiceImpl;
import com.jnevision.util.Base64Util;
import com.jnevision.util.DateUtil;

/**
 * <p>
 * 随手拍 前端控制器
 * </p>
 *
 * @author gavin
 * @since 2019-07-16
 */

@RestController
@RequestMapping("/handclaps")
public class HandClapController extends ApiController {
    @Autowired
    private HandClapServiceImpl handClapServiceImpl;
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private DeptServiceImpl deptServiceImpl;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private OssInfo ossInfo;
    @Autowired
    private UserDeptServiceImpl userDeptServiceImpl;

    /**
     * 随手拍 提交问题任务
     * 
     * @param hand
     * @return
     */
    @PostMapping
    public R<Boolean> add(@RequestBody HandClap hand, @RequestHeader("token") String token) {
        // 处理base64多张图片
        User user = this.userServiceImpl.getLoginUser(token);
        if (user.getRoleId() != 1 && user.getRoleId() != 6) {
            int parentDeptId = this.deptServiceImpl.getProject(user.getDeptId()).getId();
            hand.setDistributorId(this.userDeptServiceImpl.getCurrentDeptLeader(parentDeptId));
        } else {
            hand.setDistributorId(user.getId());
        }

        if (StringUtils.isNotBlank(hand.getPicture())) {
            String[] pics = hand.getPicture().split("<>");

            try {
                StringJoiner picUrls = new StringJoiner("<>");
                for (String pic : pics) {
                    LandOss landOss = new LandOss(redisTemplate);
                    Oss oss = landOss.getLandOss(OssType.ALI, ossInfo);
                    MultipartFile file = Base64Util.base64ToMultipart(pic);
                    Result result = oss.upload(PathEnum.MATERIAL, file);
                    picUrls.add(result.getFileUrl());
                }

                hand.setPicture(picUrls.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        hand.setFinish(false);

        return this.success(this.handClapServiceImpl.save(hand));
    }

    /**
     * 任务分配
     * 
     * @param hand
     * @param token
     * @return
     */
    @PutMapping
    public R<Boolean> update(@RequestBody HandClap hand) {
        return this.success(this.handClapServiceImpl.updateById(hand));
    }

    /**
     * 完成提交
     * 
     * @param hand
     * @param token
     * @return
     */
    @PutMapping("/finish")
    public R<Boolean> finish(@RequestBody HandClap hand) {
        if (StringUtils.isNotBlank(hand.getFinishPic())) {
            String[] pics = hand.getFinishPic().split("<>");

            try {
                StringJoiner picUrls = new StringJoiner("<>");
                for (String pic : pics) {
                    LandOss landOss = new LandOss(redisTemplate);
                    Oss oss = landOss.getLandOss(OssType.ALI, ossInfo);
                    MultipartFile file = Base64Util.base64ToMultipart(pic);
                    Result result = oss.upload(PathEnum.MATERIAL, file);
                    picUrls.add(result.getFileUrl());
                }

                hand.setFinishPic(picUrls.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        hand.setFinish(true);
        hand.setFinishTime(DateUtil.getNormalTime());
        return this.success(this.handClapServiceImpl.updateById(hand));
    }

    /**
     * 查询任务详情
     * 
     * @param id
     * @return
     */
    @GetMapping
    public R<HandClap> get(String id) {
        HandClap clap = this.handClapServiceImpl.getById(id);

        User byId = userServiceImpl.getById(clap.getDistributorId());
        clap.setDistributor(byId.getName());
        clap.setPictures(clap.getPicture().split("<>"));
        return this.success(clap);
    }

    /**
     * 查询可以被当前用户分配的任务
     * 
     * @param token
     * @return
     */
    @GetMapping("/distributed")
    public R<IPage<HandClap>> getToBeDistributed(Page<HandClap> page, @RequestHeader("token") String token,
        boolean isFinish) {
        User user = this.userServiceImpl.getLoginUser(token);
        IPage<HandClap> hlPage = this.handClapServiceImpl.page(page, new QueryWrapper<HandClap>()
            .eq("distributor_id", user.getId()).eq("is_finish", isFinish).isNotNull("is_finish"));

        hlPage.getRecords().forEach(hl -> {
            if (StringUtils.isNotBlank(hl.getUserId())) {
                hl.setUserName(this.userServiceImpl.getById(hl.getUserId()).getName());
            }

            if (StringUtils.isNotBlank(hl.getDistributorId())) {
                hl.setDistributor(this.userServiceImpl.getById(hl.getDistributorId()).getName());
            }

            if (StringUtils.isNotBlank(hl.getFinishId())) {
                hl.setFinishName(this.userServiceImpl.getById(hl.getFinishId()).getName());
            }
        });

        return this.success(hlPage);
    }

    /**
     * 查询个人任务的完成情况
     * 
     * @param page
     * @param token
     * @param isFinish
     * @return
     */
    @GetMapping("/completed")
    public R<IPage<HandClap>> getToBeCompleted(Page<HandClap> page, @RequestHeader("token") String token,
        boolean isFinish) {
        User user = this.userServiceImpl.getLoginUser(token);
        IPage<HandClap> hlPage = this.handClapServiceImpl.page(page,
            new QueryWrapper<HandClap>().eq("finish_id", user.getId()).eq("is_finish", isFinish));

        hlPage.getRecords().forEach(hl -> {
            if (StringUtils.isNotBlank(hl.getDistributorId())) {
                hl.setDistributor(this.userServiceImpl.getById(hl.getDistributorId()).getName());
            }

            if (StringUtils.isNotBlank(hl.getUserId())) {
                hl.setUserName(this.userServiceImpl.getById(hl.getUserId()).getName());
            }

            if (StringUtils.isNotBlank(hl.getFinishId())) {
                hl.setFinishName(this.userServiceImpl.getById(hl.getFinishId()).getName());
            }
        });

        return this.success(hlPage);
    }

    /**
     * pc端反馈问题查询
     * 
     * @param page
     * @param query
     * @return
     */
    @GetMapping("/page")
    public R<IPage<HandClap>> page(Page<HandClap> page, CommonQuery query) {
        IPage<HandClap> hlPage = this.handClapServiceImpl.page(page, query);
        hlPage.getRecords().forEach(hl -> {
            // if (StringUtils.isNotBlank(hl.getDistributorId())) {
            // hl.setDistributor(this.userServiceImpl.getById(hl.getDistributorId()).getName());
            // }

            if (StringUtils.isNotBlank(hl.getUserId())) {
                hl.setUserName(this.userServiceImpl.getById(hl.getUserId()).getName());
            }

            if (StringUtils.isNotBlank(hl.getFinishId())) {
                hl.setFinishName(this.userServiceImpl.getById(hl.getFinishId()).getName());
            }
        });

        return this.success(hlPage);
    }

    /**
     * pc端已分配问题查询
     * 
     * @param page
     * @param query
     * @return
     */
    @GetMapping("/page/distributed")
    public R<IPage<HandClap>> pageDistributed(Page<HandClap> page, CommonQuery query) {
        IPage<HandClap> hlPage = this.handClapServiceImpl.pageDistributed(page, query);
        hlPage.getRecords().forEach(hl -> {
            if (StringUtils.isNotBlank(hl.getDistributorId())) {
                hl.setDistributor(this.userServiceImpl.getById(hl.getDistributorId()).getName());
            }

            if (StringUtils.isNotBlank(hl.getUserId())) {
                hl.setUserName(this.userServiceImpl.getById(hl.getUserId()).getName());
            }

            if (StringUtils.isNotBlank(hl.getFinishId())) {
                hl.setFinishName(this.userServiceImpl.getById(hl.getFinishId()).getName());
            }
        });

        return this.success(hlPage);
    }
}
